package vip.manda.framework.data.repository;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ClassUtil;
import org.apache.ibatis.annotations.Mapper;
import vip.manda.framework.bean.BeanContainer;
import vip.manda.framework.bean.BeanFactory;
import vip.manda.framework.core.Application;
import vip.manda.framework.core.Function;
import vip.manda.framework.log.Log;
import vip.manda.framework.log.LogFactory;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author hongda.li 2022-04-02 17:40
 */
@Function(order = Function.Common.BEAN_FUNCTION - 10)
public class MybatisFunction implements Function.FunctionMethod {
    private static final Log log = LogFactory.getLog();

    @Override
    public void doFunction(Set<Class<?>> classes) {
        // 自动识别是否引入Mybatis
        if (ClassUtil.scanPackage("org.apache.ibatis.executor.Executor").size() == 0){
            return;
        }
        Set<Class<?>> mappers = Application.getInterfaces()
                .stream()
                .filter(clazz -> AnnotationUtil.hasAnnotation(clazz, Mapper.class))
                .collect(Collectors.toSet());
        log.func("execute function[{}]", MybatisFunction.class.getName());
        MybatisBuilder.initSqlSessionFactory(mappers);
        BeanContainer container = BeanFactory.getContainer();
        mappers.forEach(mapper -> {
            log.info("Capture mapper[{}]", mapper.getName());
            container.setBean(MybatisBuilder.buildSession(true).getMapper(mapper));
        });
    }
}
